/* SiteBrowser.m - Web site table browser
 *
 * Copyright (C) 2008 Yuuichi Teranishi
 *
 * This file is derived from Stumbler, a program developed by iphone-wireless
 * project.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2
 * published by the Free Software Foundation.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; If not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#import <CoreFoundation/CoreFoundation.h>
#import "SiteBrowser.h"
#import "SiteTable.h"

@implementation SiteBrowser 
- (id)initWithFrame:(struct CGRect)frame{
  if ((self == [super initWithFrame: frame]) != nil) {
    sites = [ [ NSMutableArray alloc] init ];

    UITableColumn *col = [ [ UITableColumn alloc ]
			   initWithTitle: @"Sites"
			   identifier:@"site"
			   width: frame.size.width
			   ];

    siteTable = [ [ SiteTable alloc] initWithFrame: 
				     CGRectMake(0, 0,
						frame.size.width,
						frame.size.height)];
    [ siteTable addTableColumn: col ];
    [ siteTable setSeparatorStyle: 1 ];
    [ siteTable setDelegate: self ];
    [ siteTable setDataSource: self ];
    [ self addSubview: siteTable ];
  }
  return self;
}

// 0...undefined
// 1...allowed
// 2...denied
- (int)permissionForSite:(NSString *)site {
  int i;
  NSString *url = [[[[site componentsSeparatedByString:@"#"]
		      objectAtIndex: 0]
		     componentsSeparatedByString:@"?"]
		    objectAtIndex: 0];
  
  for (i = 0; i < [sites count]; i ++) {
    if ([[[sites objectAtIndex: i] objectForKey: @"name"]
	  isEqualToString: url]) {
      if ([[[sites objectAtIndex: i] objectForKey: @"permission"] boolValue]) {
	return 1;
      }
      else {
	return 2;
      }
    }
  }
  return 0;
}

- (void)setOpenURLDelegate:(id)delegate {
  _delegate = delegate;
}

- (void)tableRowSelected:(NSNotification *)notification {
  NSString *url = [ self selectedURL ];
  // hasPrefix: does not work.
  if (url != nil && [url hasPrefix: @"http://"])
    [ _delegate openURL: [NSURL URLWithString: url]];
}

- (NSDate *)selectedURL {
  if ([ siteTable selectedRow ] == -1)
    return nil;
  return [[ sites objectAtIndex: [ siteTable selectedRow ]]
	   objectForKey: @"name"];
}

- (void)dealloc {
  [ sites release ];
  [ siteTable release ];
  [super dealloc];
}

- (void)addSite:(NSString *)site permission:(BOOL)permission {
  int i;
  NSDictionary *found = nil;

  NSString *url = [[[[site componentsSeparatedByString:@"#"]
		      objectAtIndex: 0]
		     componentsSeparatedByString:@"?"]
		    objectAtIndex: 0];

  for (i = 0; i < [sites count]; i++) {
    if ([[[sites objectAtIndex: i] objectForKey: @"name"]
	  isEqualToString: url]) {
      found = [sites objectAtIndex: i];
      break;
    }
  }
  if (found != nil) {
    [ sites removeObject: found];
  }
  [ sites addObject:
	    [NSDictionary dictionaryWithObjectsAndKeys:
			    url, @"name", 
			  [[NSNumber alloc] initWithBool: permission], @"permission", 
			  nil] ];
  [ self saveData ];
}

- (void)saveData {
  NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
				       sites, @"value", nil];
  [ dict writeToFile: @"/var/mobile/Library/Preferences/spotter_sites.plist"
	atomically:YES]; 
}

- (void)reloadData {
  [ sites removeAllObjects ];
  //[ logdb addDatesToArray: dates ];
  NSDictionary *dict = [NSDictionary
			 dictionaryWithContentsOfFile:
			   @"/var/mobile/Library/Preferences/spotter_sites.plist"];
  NSArray *loadedSites = [dict objectForKey:@"value" ];
  int i;
  for (i = 0; i < [loadedSites count]; i++) {
    [sites addObject: [loadedSites objectAtIndex: i]];
  }
  [ siteTable reloadData ];
}

- (int)numberOfRowsInTable:(UITable *)table {
  return [ sites count ];
}

- (UITableCell *)table:(UITable *)table
	    cellForRow:(int)row
		column:(UITableColumn *)col
{
  SiteCell *cell = [ [ SiteCell alloc ] init ];
  [ cell setTable: siteTable ];
  [ cell setSites: sites ];
  UIImage *allowImage = [UIImage applicationImageNamed:@"allow.png"];
  UIImage *denyImage = [UIImage applicationImageNamed:@"deny.png"];
  [ cell setImage:
	   [[[sites objectAtIndex: row ]
	      objectForKey:@"permission"] boolValue] ? allowImage : denyImage];
  [ cell setTitle:
	   [[sites objectAtIndex: row ] objectForKey:@"name"]];
  return [ cell autorelease ];
}


@end
